dyn.load("c:/program files/tasacs/tasacsR.dll")

getparams <- function(c, i, d) sub(' +$', '',  .Fortran("getparams", result=sprintf("%-256s", c), as.integer(i), d)$result)
setstr <- function(s) .Fortran("setstr", sprintf("%-256s", s))
getstr <- function() sub(' +$', '',  .Fortran("getstr", s=character(1))$s)
seti <- function(i) .Fortran("seti", as.integer(i))
geti <- function() .Fortran("geti", i=integer(1))$i
setd <- function(d) .Fortran("setd", as.double(d))
getd <- function() .Fortran("getd", d=double(1))$d
setl <- function(l) .Fortran("setl", as.logical(l))
getl <- function() .Fortran("getl", l=logical(1))$l
modify <- function() .Fortran("modify")

loadrun <- function(projectdir, runname) .Fortran("xloadrun", sprintf("%-256s", projectdir), sprintf("%-256s", runname))
getrunprop <- function(prop) .Fortran("xgetrunprop", as.integer(prop), d=double(1))$d
getn <- function(year, age) .Fortran("xgetn", as.integer(year), as.integer(age), d=double(1))$d
getf <- function(year, age) .Fortran("xgetf", as.integer(year), as.integer(age), d=double(1))$d
getm <- function(year, age) .Fortran("xgetm", as.integer(year), as.integer(age), d=double(1))$d

runopt <- function() .Fortran("xrunopt", l=logical(1))$l

# load a run
ProjectPath <- "C:\\Projects\\tasacs\\Data\\NSSH 2008\\NSSH Final"
loadrun(ProjectPath, "Working run")

# define some properties
propFirstYear = 5
propLastYear  = 6
propFirstAge  = 8
propLastAge   = 9
propSSBFracF = 18
propSSBFracM = 19
propRunStage  = 200
propRunIter   = 201
propRunDelta  = 202
propRunObjFunc= 203

# get properties
PrintModelDimensions <-function() 
{ print(getrunprop(propFirstYear))
  print(getrunprop(propLastYear)) 
  print(getrunprop(propFirstAge)) 
  print(getrunprop(propLastAge))
}

RunModel <- function()
{ while (! runopt()) 
  { print(sprintf("Iter:%d, Delta:%f, ObjFunc:%f", 
     getrunprop(propRunIter), getrunprop(propRunDelta), getrunprop(propRunObjFunc))) 
     flush.console()
  }
} 
RunModel()

dyn.unload("c:/program files/tasacs/tasacsR.dll")

list(age=getrunprop(propFirstAge):getrunprop(propLastAge), year=getrunprop(propFirstYear):getrunprop(propLastYear))

library(FLCore)
library(FLEDA)

ReadN <- function()
{ N <- FLQuant(NA, dimnames= list(age=getrunprop(propFirstAge) : getrunprop(propLastAge),
    year=getrunprop(propFirstYear) : getrunprop(propLastYear)))
    for(i in dimnames(N)$age) {
       for(j in dimnames(N)$year) {
          N[i, j] <- getn(as.numeric(j) - getrunprop(propFirstYear), as.numeric(i) - getrunprop(propFirstAge))
       }
    }
return(N)
}

ReadF <- function()
{ H <- FLQuant(NA, dimnames= list(age=getrunprop(propFirstAge) : getrunprop(propLastAge),
    year=getrunprop(propFirstYear) : getrunprop(propLastYear)))
    for(i in dimnames(N)$age) {
       for(j in dimnames(N)$year) {
          H[i, j] <- getf(as.numeric(j) - getrunprop(propFirstYear), as.numeric(i) - getrunprop(propFirstAge))
       }
    }
return(H)
}

ReadM <- function()
{ H <- FLQuant(NA, dimnames= list(age=getrunprop(propFirstAge) : getrunprop(propLastAge),
    year=getrunprop(propFirstYear) : getrunprop(propLastYear)))
    for(i in dimnames(N)$age) {
       for(j in dimnames(N)$year) {
          H[i, j] <- getm(as.numeric(j) - getrunprop(propFirstYear), as.numeric(i) - getrunprop(propFirstAge))
       }
    }
return(H)
}



    N = ReadN()
    F = ReadF()
    M = ReadM()
    caton <- readVPAFile(paste(ProjectPath,"\\Data\\1988-2008 0-15\\caton.txt", sep=""))
    canum <- readVPAFile(paste(ProjectPath,"\\Data\\1988-2008 0-15\\canum.txt", sep=""))
    weca <- readVPAFile(paste(ProjectPath,"\\Data\\1988-2008 0-15\\weca.txt", sep=""))
    west <- readVPAFile(paste(ProjectPath,"\\Data\\1988-2008 0-15\\west.txt", sep=""))
    matprop <- readVPAFile(paste(ProjectPath,"\\Data\\1988-2008 0-15\\matprop.txt", sep=""))


    # Create the stock object
    S <- FLStock(
       stock.n = N,
       harvest = F,
       landings = caton,
       catch = caton,
       landings.n = canum,
       catch.n = canum,
       landings.wt = weca,
       catch.wt = weca,
       stock.wt = west,
       mat = matprop,
       m = M
       )
    # restore the unit of harvest
    S@harvest@units <- "f"
    harvest.spwn(S) <- 0
    m.spwn(S) <- 0
    discards(S) <- 0
    discards.n(S) <- 0
    discards.wt(S) <- 0

S.ind <- readFLIndices(paste(ProjectPath,"\\Data\\1988-2008 0-15\\fleet.txt", sep=""))

    

plot(S)

# A straight forward xyplot
xyplot(data~year|age, data=stock.wt(S), type="l")

# convert the grouping factor to type factor to display it properly in the strip
xyplot(data~year|as.factor(age), data=stock.wt(S), type="l")

# putting a legend in  ## new ##
xyplot(data~year, groups=age, data=stock.wt(S), type="l",
       key=list(lines=list(lty=1, col=1:10), text=list(lab=as.character(1:10)), columns=4))

# Box and whisker plots use bwplot
bwplot(data~year, data=stock.wt(S))

# You can also use boxplot - however for this method you will have to
# manually convert the FLQuant to a data.frame
boxplot(data~age, data=as.data.frame(stock.wt(S)))

# Add some more lines - from a Von-B fit
vb <- nls(data~((Linf*(1-exp(-k*(age-t0))))^3/1000), data=as.data.frame(stock.wt(S)),start=list(Linf=50, k=0.2, t0=0))

lines(predict(vb, list(age=1:15)), col="red", lwd=2)
title(main="Norewegian spring spawning herring Stock Weights at Age")

## Use xyplot for more flexibility
xyplot(data~year|qname,groups=age,data=(FLQuants(m=m(S),mat=mat(S),wt=stock.wt(S),catch.n=catch.n(S))),scale="free",type="l")

## look for year-classes
bubbles(age ~ year | unit, spay(catch.n(S)), main="year classes",bub.scale = 3.5)

## look for trends in weights
xyplot(data~year|unit, data=catch.wt(S), groups=age, type="l", lty=1, col=1)

#log transformed catch at age data plotted by cohort
plot(trim(FLCohort(log(catch.n(S))), cohort=1988:2000, age=1:10))

# log catch ratios
stk.logcr <- logcc(catch.n(S))
xyplot(data~age|unit, data=trim(stk.logcr, cohort=1980:1999, age=1:12), groups=cohort,
          main          =list(label="Log catch ratio for NSSH", cex=1),
          ylab          =list(label="log ratio", cex=0.8),
          xlab          =list(cex=0.8),
          par.strip.text=list(cex=0.8),
          scales        =list(cex=0.7),
          type="l", col=1)
          
#Index 1. Log catch ratio for Spawning grounds along the Norwegian coaste
S.ind <- readFLIndices(paste(ProjectPath,"\\Data\\fleet.txt", sep=""))
idx.logcr1<-logcc(index(S.ind[[1]]))
xyplot(data~age|unit, data=idx.logcr, groups=cohort,
          main          =list(label="Log catch ratio for Spawning grounds along the Norwegian coast", cex=1),
          ylab          =list(label="log ratio", cex=0.8),
          xlab          =list(cex=0.8),
          par.strip.text=list(cex=0.8),
          scales        =list(cex=0.7),
          type="l", col=1)

#Index 2. Wintering area in Vestfjorden in November-December
idx.logcr2<-logcc(index(S.ind[[2]]))
xyplot(data~age|unit, data=idx.logcr, groups=cohort,
          main          =list(label="Log catch ratio for Wintering area in Vestfjorden in November-December", cex=1),
          ylab          =list(label="log ratio", cex=0.8),
          xlab          =list(cex=0.8),
          par.strip.text=list(cex=0.8),
          scales        =list(cex=0.7),
          type="l", col=1)
          
#Index 3. Wintering area in Vestfjorden in January
idx.logcr3<-logcc(index(S.ind[[3]]))
xyplot(data~age|unit, data=idx.logcr, groups=cohort,
          main          =list(label="Log catch ratio for Wintering area in Vestfjorden in January", cex=1),
          ylab          =list(label="log ratio", cex=0.8),
          xlab          =list(cex=0.8),
          par.strip.text=list(cex=0.8),
          scales        =list(cex=0.7),
          type="l", col=1)

#Index 4. Wintering area in Vestfjorden in January
catch.n(S.ind[[4]])
idx.logcr4<-logcc(index(S.ind[[4]]))
xyplot(data~age|unit, data=idx.logcr, groups=cohort,
          main          =list(label="Young herring in the Barents Sea in May", cex=1),
          ylab          =list(label="log ratio", cex=0.8),
          xlab          =list(cex=0.8),
          par.strip.text=list(cex=0.8),
          scales        =list(cex=0.7),
          type="p", col=1)

# The following doesnt work. Is followed up by R. Scott...
xyplot(data~age|unit, groups=qname, data=FLQuants(a=idx.logcr1, b=idx.logcr2), type="l")

plot(ssb(S), type="l")
plot(fbar(S), type="l")
plot(S)



filecon <- file(paste(ProjectPath,"\\Working run\\summary.txt", sep=""), open="r")
lines <- readLines(filecon)
numlines <- length(lines)
close(filecon)

filecon <- file(paste(ProjectPath,"\\Working run\\summary.txt", sep=""), open="r")
for(i in 1:numlines) {
   tt <- scan(filecon, what='character', nlines=1, quiet=TRUE)
   
   cat(tt, '\n')
   
}
close(filecon)
